package com.chixing.server.listener;

import com.alibaba.fastjson.JSON;
import com.chixing.mapper.FlowMapper;
import com.chixing.mapper.MyCouponMapper;
import com.chixing.mapper.MyOrderMapper;
import com.chixing.pojo.*;
import com.chixing.util.DateUtil;
import com.chixing.server.sender.Sender;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    /**
     * 针对redis数据失效事件，进行数据处理
     * @param message
     * @param pattern
     */
    @Autowired
    private Sender sender;
    @Autowired
    private MyCouponMapper myCouponMapper;
    @Autowired
    private MyOrderMapper myOrderMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private FlowMapper flowMapper;
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();
//        System.out.println(expiredKey);
        MyOrder myOrder;
        if(expiredKey.contains("myOrder_")){
            String id = expiredKey.replace("myOrder_","");
            int myOrderId = Integer.valueOf(id);
            myOrder = myOrderMapper.selectByPrimaryKey(myOrderId);
            // 将之前未推送成功的信息status设置为1
            RequestMessage requestMessageExample = new RequestMessage();
            requestMessageExample.setStatus(0);
            requestMessageExample.setRoom(myOrder.getCustId().toString());
            Query query = new Query(Criteria.byExample(requestMessageExample));
            Update update = new Update().set("status",1);
            mongoTemplate.updateMulti(query,update,RequestMessage.class);


            RequestMessage requestMessage = new RequestMessage();
            requestMessage.setRoom(myOrder.getCustId().toString());
            requestMessage.setUserId("000");
            requestMessage.setType("2");
            requestMessage.setQuestionId("questionId");
            requestMessage.setCreateTime(DateUtil.dateToString(myOrder.getMyOrderTime(),DateUtil.DATE_PATTEN_YMDHMS));
            requestMessage.setContent("您已经超出取车时间未还车，记得及时归还！");
            sender.send(JSON.toJSONString(requestMessage));
        }

        //优惠券过期后持久化到数据库，设置状态为已失效
        if(expiredKey.contains("myCoupon_")){
            String id = expiredKey.replace("myCoupon_","");
            int myCouponId = Integer.valueOf(id);
            MyCoupon myCoupon = myCouponMapper.selectByPrimaryKey(myCouponId);
            myCoupon.setStatus(2);
            myCouponMapper.updateByPrimaryKey(myCoupon);
        }

        //订单过期后持久化到数据库，设置状态为已取消
        if(expiredKey.contains("myOrderNum_")){
            String id = expiredKey.replace("myOrderNum_","myOrderId_");
            MyOrder myOrder1 = (MyOrder) redisTemplate.opsForValue().get(id);
            System.out.println(myOrder1);
//            redisTemplate.opsForValue
            if(myOrder1.getStatus() == 2){
                //订单成功支付，进入支付成功队列
                rabbitTemplate.convertAndSend("orderSuccessPayExchange","orderSuccessPayRouting",JSON.toJSONString(myOrder1));
            }
            if(myOrder1.getStatus() == 3){
                System.out.println("未支付，失效");
                //订单还未支付，设置为已失效，进入订单支付失败队列
                myOrder1.setStatus(4);
                rabbitTemplate.convertAndSend("orderFailPayExchange","orderFailPayRouting",JSON.toJSONString(myOrder1));
            }
//            myOrderMapper.updateByPrimaryKey(myOrder1);
        }

        // 添加流水
        if(expiredKey.contains("flowId2_")){
            String redisFlowKey = expiredKey.replace("flowId2_","flowId_");
            Flow flow = (Flow)redisTemplate.opsForValue().get(redisFlowKey);
            rabbitTemplate.convertAndSend("insertFlowExchange","insertFlowRouting",JSON.toJSONString(flow));
        }

        if(expiredKey.contains("storeCarUpdate")){
            String redisStoreCarKey = expiredKey.replace("storeCarUpdate","-storeCar-");
            StoreCar storeCar = (StoreCar) redisTemplate.opsForValue().get(redisStoreCarKey);
            rabbitTemplate.convertAndSend("updateStoreCarExchange","updateStoreCarRouting",JSON.toJSONString(storeCar));
        }
    }
}